<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header">
        <span>综合能源数据采集演示</span>
      </div>

      <!-- 设备选择 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-select v-model="selectedDevice" placeholder="请选择设备" style="width: 100%;" @change="handleDeviceChange">
            <el-option
              v-for="device in deviceList"
              :key="device.deviceId"
              :label="device.deviceName + ' (' + device.deviceCode + ')'"
              :value="device"
            >
              <span style="float: left">{{ device.deviceName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <dict-tag :options="dict.type.ems_energy_type" :value="device.energyType"/>
              </span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="getDeviceList">刷新设备</el-button>
        </el-col>
      </el-row>

      <!-- 电力数据采集 -->
      <el-collapse v-model="activeNames">
        <el-collapse-item title="电力数据采集" name="electric" v-if="canShowElectric">
          <el-form :model="electricForm" label-width="120px" size="small">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="电压(V)">
                  <el-input-number v-model="electricForm.voltage" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="电流(A)">
                  <el-input-number v-model="electricForm.current" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="功率(kW)">
                  <el-input-number v-model="electricForm.power" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="电能(kWh)">
                  <el-input-number v-model="electricForm.energy" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="功率因数">
                  <el-input-number v-model="electricForm.powerFactor" :precision="3" :step="0.001" :max="1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="频率(Hz)">
                  <el-input-number v-model="electricForm.frequency" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="sendElectricData" :loading="electricLoading">发送电力数据</el-button>
              <el-button @click="generateElectricData">生成模拟数据</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>

        <!-- 水力数据采集 -->
        <el-collapse-item title="水力数据采集" name="water" v-if="canShowWater">
          <el-form :model="waterForm" label-width="120px" size="small">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="流量(L/s)">
                  <el-input-number v-model="waterForm.flowRate" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用水量(m³)">
                  <el-input-number v-model="waterForm.waterConsumption" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="水压(MPa)">
                  <el-input-number v-model="waterForm.waterPressure" :precision="2" :step="0.01" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="水温(℃)">
                  <el-input-number v-model="waterForm.waterTemperature" :precision="1" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="sendWaterData" :loading="waterLoading">发送水力数据</el-button>
              <el-button @click="generateWaterData">生成模拟数据</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>

        <!-- 燃气数据采集 -->
        <el-collapse-item title="燃气数据采集" name="gas" v-if="canShowGas">
          <el-form :model="gasForm" label-width="120px" size="small">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="燃气流量(m³/h)">
                  <el-input-number v-model="gasForm.gasFlow" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="燃气用量(m³)">
                  <el-input-number v-model="gasForm.gasConsumption" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="燃气压力(kPa)">
                  <el-input-number v-model="gasForm.gasPressure" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="燃气温度(℃)">
                  <el-input-number v-model="gasForm.gasTemperature" :precision="1" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="热值(MJ/m³)">
                  <el-input-number v-model="gasForm.calorificValue" :precision="2" :step="0.1" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button type="primary" @click="sendGasData" :loading="gasLoading">发送燃气数据</el-button>
              <el-button @click="generateGasData">生成模拟数据</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>

    </el-card>

    <!-- 发送日志 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header">
        <span>发送日志</span>
        <el-button style="float: right; margin-top: -5px;" size="mini" @click="clearLogs">清空日志</el-button>
      </div>
      <el-timeline>
        <el-timeline-item
          v-for="(log, index) in logs"
          :key="index"
          :timestamp="log.time"
          :type="log.type"
        >
          {{ log.message }}
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script>
import { listDevice } from "@/api/energy/device";
import request from '@/utils/request';

export default {
  name: "DataCollection",
  dicts: ['ems_energy_type'],
  data() {
    return {
      activeNames: ['electric'],
      deviceList: [],
      selectedDevice: null,
      electricLoading: false,
      waterLoading: false,
      gasLoading: false,
      logs: [],
      electricForm: {
        voltage: 220.5,
        current: 10.2,
        power: 2.25,
        energy: 100.5,
        powerFactor: 0.95,
        frequency: 50.0
      },
      waterForm: {
        flowRate: 5.5,
        waterConsumption: 120.8,
        waterPressure: 0.6,
        waterTemperature: 25.3
      },
      gasForm: {
        gasFlow: 15.2,
        gasConsumption: 85.6,
        gasPressure: 2.5,
        gasTemperature: 22.1,
        calorificValue: 35.8
      }
    };
  },
  computed: {
    canShowElectric() {
      return !this.selectedDevice || this.selectedDevice.energyType === '1';
    },
    canShowWater() {
      return !this.selectedDevice || this.selectedDevice.energyType === '2';
    },
    canShowGas() {
      return !this.selectedDevice || this.selectedDevice.energyType === '3';
    }
  },
  created() {
    this.getDeviceList();
  },
  methods: {
    /** 查询设备列表 */
    getDeviceList() {
      listDevice({ status: '0' }).then(response => {
        this.deviceList = response.rows;
      });
    },
    
    /** 设备变更 */
    handleDeviceChange(device) {
      this.selectedDevice = device;
      // 根据设备类型打开对应面板
      if (device) {
        switch (device.energyType) {
          case '1':
            this.activeNames = ['electric'];
            break;
          case '2':
            this.activeNames = ['water'];
            break;
          case '3':
            this.activeNames = ['gas'];
            break;
        }
      }
    },

    /** 发送电力数据 */
    sendElectricData() {
      if (!this.selectedDevice) {
        this.$modal.msgError('请先选择设备');
        return;
      }
      if (this.selectedDevice.energyType !== '1') {
        this.$modal.msgError('所选设备不是电力设备');
        return;
      }

      this.electricLoading = true;
      const data = {
        deviceCode: this.selectedDevice.deviceCode,
        energyType: '1',
        ...this.electricForm,
        collectTime: new Date().getTime()
      };

      request({
        url: '/energy/collection/electric',
        method: 'post',
        data: data
      }).then(response => {
        this.addLog('success', `电力数据发送成功：${response.msg}`);
        this.$modal.msgSuccess('电力数据发送成功');
      }).catch(error => {
        this.addLog('danger', `电力数据发送失败：${error.message || '网络错误'}`);
        this.$modal.msgError('电力数据发送失败');
      }).finally(() => {
        this.electricLoading = false;
      });
    },

    /** 发送水力数据 */
    sendWaterData() {
      if (!this.selectedDevice) {
        this.$modal.msgError('请先选择设备');
        return;
      }
      if (this.selectedDevice.energyType !== '2') {
        this.$modal.msgError('所选设备不是水力设备');
        return;
      }

      this.waterLoading = true;
      const data = {
        deviceCode: this.selectedDevice.deviceCode,
        energyType: '2',
        ...this.waterForm,
        collectTime: new Date().getTime()
      };

      request({
        url: '/energy/collection/water',
        method: 'post',
        data: data
      }).then(response => {
        this.addLog('success', `水力数据发送成功：${response.msg}`);
        this.$modal.msgSuccess('水力数据发送成功');
      }).catch(error => {
        this.addLog('danger', `水力数据发送失败：${error.message || '网络错误'}`);
        this.$modal.msgError('水力数据发送失败');
      }).finally(() => {
        this.waterLoading = false;
      });
    },

    /** 发送燃气数据 */
    sendGasData() {
      if (!this.selectedDevice) {
        this.$modal.msgError('请先选择设备');
        return;
      }
      if (this.selectedDevice.energyType !== '3') {
        this.$modal.msgError('所选设备不是燃气设备');
        return;
      }

      this.gasLoading = true;
      const data = {
        deviceCode: this.selectedDevice.deviceCode,
        energyType: '3',
        ...this.gasForm,
        collectTime: new Date().getTime()
      };

      request({
        url: '/energy/collection/gas',
        method: 'post',
        data: data
      }).then(response => {
        this.addLog('success', `燃气数据发送成功：${response.msg}`);
        this.$modal.msgSuccess('燃气数据发送成功');
      }).catch(error => {
        this.addLog('danger', `燃气数据发送失败：${error.message || '网络错误'}`);
        this.$modal.msgError('燃气数据发送失败');
      }).finally(() => {
        this.gasLoading = false;
      });
    },

    /** 生成电力模拟数据 */
    generateElectricData() {
      this.electricForm = {
        voltage: (200 + Math.random() * 40).toFixed(1),
        current: (8 + Math.random() * 4).toFixed(2),
        power: (1.5 + Math.random() * 2).toFixed(2),
        energy: (80 + Math.random() * 40).toFixed(1),
        powerFactor: (0.85 + Math.random() * 0.15).toFixed(3),
        frequency: (49.5 + Math.random() * 1).toFixed(1)
      };
    },

    /** 生成水力模拟数据 */
    generateWaterData() {
      this.waterForm = {
        flowRate: (3 + Math.random() * 5).toFixed(1),
        waterConsumption: (100 + Math.random() * 50).toFixed(1),
        waterPressure: (0.4 + Math.random() * 0.4).toFixed(2),
        waterTemperature: (20 + Math.random() * 10).toFixed(1)
      };
    },

    /** 生成燃气模拟数据 */
    generateGasData() {
      this.gasForm = {
        gasFlow: (10 + Math.random() * 10).toFixed(1),
        gasConsumption: (60 + Math.random() * 40).toFixed(1),
        gasPressure: (2 + Math.random() * 1).toFixed(1),
        gasTemperature: (18 + Math.random() * 8).toFixed(1),
        calorificValue: (34 + Math.random() * 4).toFixed(1)
      };
    },

    /** 添加日志 */
    addLog(type, message) {
      this.logs.unshift({
        type: type,
        time: new Date().toLocaleString(),
        message: message
      });
      // 限制日志数量
      if (this.logs.length > 20) {
        this.logs = this.logs.slice(0, 20);
      }
    },

    /** 清空日志 */
    clearLogs() {
      this.logs = [];
    }
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
</style> 